import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Article } from './article.schema';
import { QueryDto, ArticleDto } from './article.dto';
import { calcTagArticleCountAggregate } from './article.aggregate';

@Injectable()
export class ArticleService {
  constructor(
    @InjectModel(Article.name) private articleModel: Model<Article>,
  ) {}

  async findAll(): Promise<Article[]> {
    return this.articleModel.find().exec();
  }

  async findOne(id: string): Promise<Article> {
    return this.articleModel.findById(id).exec();
  }

  async findByCondition(condition: QueryDto): Promise<Article[]> {
    const { limit, page, filter } = condition;
    const skip = (page - 1) * limit;
    const filterObj = JSON.parse(filter);
    console.log('filterObj', filterObj);
    return this.articleModel.find(filterObj).skip(skip).limit(limit).exec();
  }

  /**
   * @description 统计指定tag的文章数量
   */
  async calcTagArticleCount(
    tags: string[],
  ): Promise<{ tag: string; count: number }[]> {
    return this.articleModel.aggregate(calcTagArticleCountAggregate(tags));
  }

  async create(article: ArticleDto): Promise<Article> {
    const createdArticle = new this.articleModel(article);
    return createdArticle.save();
  }

  async update(id: string, article: Article): Promise<Article> {
    return this.articleModel
      .findByIdAndUpdate(id, article, { new: true })
      .exec();
  }

  async delete(id: string): Promise<Article> {
    return this.articleModel.findByIdAndDelete(id).exec();
  }
}
